<template>
  <Validator ref="refStep1" @submit="changeCurStep(2)"></Validator>
  <SealSelector
    purpose="continued"
    ref="refStep2"
    @createHoverSeal="setStatus('prevSubmit')"
    @submit="doSealAdd"
  ></SealSelector>
</template>
<script setup>
import { reactive, toRefs, ref, inject, onMounted, watchEffect } from "vue";
import { useEventListener } from "@vueuse/core";
import Validator from "./_validator.vue";
import SealSelector from "./_sealSelector.vue";
import { seal, ss } from "@/utils";
import $ from "jquery";

const provideHome = inject("provideHome");
const refStep1 = ref();
const refStep2 = ref();
const state = reactive({
  style: {},
  status: "",
  formData: {},
});
const { style, formData } = toRefs(state);

const changeCurStep = curStep => {
  refStep1.value.close();
  refStep2.value.close();
  if (curStep == 1) {
    refStep1.value.show();
  } else if (curStep == 2) {
    refStep2.value.show();
  }
  setTimeout(() => {
    provideHome.methods.setSealCurrentOperateName("btnSealAddContinued");
  }, 30);
};

let timer;
watchEffect(() => {
  let { status } = state;
  if (status == "prevSubmit") {
    //提交的上一步
    $("#tipsSealAddContinued").show();
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      $("#tipsSealAddContinued").hide();
    }, 3000);
  } else {
    $("#tipsSealAddContinued").hide();
  }
});

const setStatus = newStatus => {
  state.status = newStatus;
};

const doSealAdd = async params => {
  let { sealInfo, posInfo } = params;

  await seal.doSealAdd({
    fileId: ss.get("fileId"),
    signatureInfo: {
      signatureType: "custom",
      page: posInfo.page,
      x: posInfo.left,
      y: posInfo.top,
    },
    sealSn: sealInfo.sealSn,
    positionType: 1,
    signContinued: "01", //连续签章
    sealType: sealInfo.sealType,
  });
};

const execExitEvents = () => {
  if (state.status == "prevSubmit") {
    provideHome.methods.setSealCurrentOperateName("");
    refStep1.value.close();
    refStep2.value.close();
    seal.exitAppLinkWhenSealAdd();
    setStatus("");
  }
};

//退出事件
const bindExitEvents = () => {
  useEventListener(document, "keyup", evt => {
    if (evt.code == "Escape") {
      //ESC按键
      // console.log("按下了 ESC 键 ...");
      execExitEvents();
    }
  });

  useEventListener(document, "contextmenu", evt => {
    // console.log("鼠标右键点击 ...");
    execExitEvents();
  });
};

onMounted(() => {
  bindExitEvents();
});

defineExpose({
  show() {
    changeCurStep(1);

    //kings mock
    // changeCurStep(2);
  },
});
</script>
<style lang="scss"></style>
